package com.teach.util;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.common.bean.Response;
import com.common.utils.JsonUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.StringUtils;


/**
 * token过滤器
 */
@WebFilter(urlPatterns = { "/*" })
public class TokenFilter implements Filter {

	private final static Logger log = LoggerFactory.getLogger(TokenFilter.class);

	private final static AntPathMatcher MATCHER = new AntPathMatcher();

	@Value("${token.filter.uri:}")
	public String[] allowUri;

	@Override
	public void init(FilterConfig filterConfig) {
	}

	@Override
	public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
			throws IOException, ServletException {
		HttpServletResponse response = (HttpServletResponse) res;
		HttpServletRequest request = (HttpServletRequest) req;

		// 检查过滤的URI
		String uri = request.getRequestURI();
		if ("/".equals(uri)) {
			chain.doFilter(req, res);
		}

		boolean allow = false;
		if (!StringUtils.isEmpty(allowUri)) {
			for (String pass : allowUri) {
				if (pass.indexOf("*") > 0) {
					if (MATCHER.match(pass, uri)) {
						log.info("Token Filter Pass uri :{}", uri);
						allow = true;
						break;
					}
				} else {
					if (pass.equals(uri)) {
						log.info("Token Filter Pass uri :{}", uri);
						allow = true;
						break;
					}
				}
			}
		}

		if (!allow) {
			// token校验
			String authorization = request.getHeader("Authorization");
			if (null == authorization) {
				doAuthFailedResponse(response, Response.fail("token校验失败"));
				return;
			}
		}

		chain.doFilter(req, res);
	}

	private void doAuthFailedResponse(HttpServletResponse response, Response<Void> resp) throws IOException {
		response.setStatus(HttpStatus.OK.value());
		response.setCharacterEncoding("UTF-8");
		response.setContentType("application/json; charset=utf-8");

		response.setHeader("Access-Control-Allow-Origin", "*");
		response.setHeader("Cache-Control", "no-cache");
		String allowHeaders = "Origin, No-Cache, X-Requested-With, If-Modified-Since, Pragma, Last-Modified, Cache-Control, Expires, Content-Type, X-E4M-With, Authorization";
		response.addHeader("Access-Control-Allow-Headers", allowHeaders);
		response.addHeader("Access-Control-Allow-Methods", "*");

		PrintWriter out = response.getWriter();
		out.append(JsonUtils.toJson(resp));
	}

	@Override
	public void destroy() {
	}
}